#!/bin/bash
#
#  Volodymyr P Sergiievskyi, voov.rat@gmail.com
#
#  Reorder the gvv file,which is produced by AmberTools 1DRISM program to the format, used in rism-mol (& RISM-MOL 3D) program.
#
#  Let we have atoms 1,2,3,4
#  and RDFs g11, g12, g13, g14,...
#
#  RISM-MOL order is:
#
#  g11, g12, g13, g14, g22, g23, g24, g33, g34, g44
#
#  AmberTools order is:
#
#  g11, g12, g22, g13, g23, g33, g14, g24, g34, g44
#
#  The orders can be more understandable, if we write the RDFs in the table:
# 
#      1   2    3     4
#  1  g11  g12  g13  g14
#  2       g22  g23  g24
#  3            g33  g34
#  4                 g44
#
#   In RISM-MOL order (rdf file) the RDFs are presented row-by row    
#   In AmberTools (gvv file)  order - column by column
#
#  This script generates the  gawk command to reorder the RDFs and then - run it...
# 

echo USAGE:   ./gvv2rismmolRDFs  mol.gvv mol.rdf

function countCols
{
  echo $#
}

#$A=$(countCols $(head -n 1 $1))

A=$( head -n 1 $1 | tr ' ' $'\n' | grep [0-9] | wc -l )



N=$(echo "scale=10;sqrt(2*($A-1)+1/4)-1/2" | bc | xargs printf "%1.0f" )

#echo $N

K="'"
KK='"'
USD='$'
SP=$KK'\t'$KK

S="gawk $K{ print "$USD"1$SP"

# To transform - we just need write numbers with dynamic stride: n-1, n-2.... 1
#
k0=1

for ((i=1;i<=$N;i++))
do
	k0=$(($k0 + $i));
#	stride=$(($N-1))
	stride=$i

	k=$k0
 	for ((j=$i;j<=$N;j++))
	do
			
		S=$S' $'$k$SP
		k=$(($k+$stride))
		stride=$(($stride+1))		

	done 

done

S=$S"}'"
#echo $S

S="cat $1 | $S > $2"
echo $S
eval  $S  

